import axios from 'axios'
import { Message } from 'element3'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, 
  timeout: 5000
})
service.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers['Authorization'] = 'token ' + getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(

  response => {
    return response
  },
  error => {
    if (error.response.status == '401') {
      store.dispatch('resetToken').then(() => {
        location.reload()
      })
    }
    Message({
      message: error.response.data.message ? error.response.data.message[0] : error.response.data.detail,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error.response)
  }
)

export default service
